import Utils from '../utils/index';
import Dom from '../utils/Dom';

/**
 * 遮罩层，用于在弹窗、ContextMenu 时覆盖一层背景层，方便用户进行点击关闭相应的 弹窗、ContextMenu
 */
class Dimmer {
    /**
     * @param callback 点击回调函数
     * @param options 配置
     *  - autoDestory 是否自定销毁
     *  - opacity 透明度
     *  - zIndex 层叠值，默认是 9999
     */
    constructor(callback, options) {
        this.callback = callback;
        this.userOptions = Utils.extend({
            autoDestory: false,
            ignoreClick: false,
        }, options);

        this.el = Dom.append(document.body, 'div', 'dimmer', null);

        let style = {};
        if (this.userOptions.opacity) {
            style.opacity = this.userOptions.opacity;
        }

        if (this.userOptions.zIndex) {
            style.zIndex = this.userOptions.zIndex;
        }

        if (!Utils.isObjEmpty(style)) {
            Dom.styles(this.el, style);
        }

        if (this.userOptions.ignoreClick) {
            return false;
        }

        this.unbinder = Dom.addEvent(this.el, 'click', e => {
            if (Utils.isFn(this.callback)) {
                this.callback();
            }

            if (this.userOptions.autoDestory) {
                this.destory();
            } else {
                this.show(true);
            }
            return Dom.nodefault(e);
        });

        // Dom.addEvent(this.el, 'contextmenu', e => {
        //     return Dom.nodefault(e);
        // })
    }

    // 销毁
    destory() {
        // 销毁事件
        if (this.unbinder) {
            this.unbinder();
            this.unbinder = false;
        }

        // 销毁 Dom
        setTimeout(() => {
            if (this.el.parentNode) {
                this.el.parentNode.removeChild(this.el);
            }
        }, 300)
    }

    /** 
     * 显示或隐藏
     *  @param isHide 是否是隐藏操作 
     */
    show(isHide) {
        this.el.style.display = isHide ? 'none' : 'block'
    }

}

export default Dimmer;